<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        progress{
            display: none;
        }
    </style>
</head>

<body>
    <form action="">
        <input type="text" name="username" value="admin">
        <input type="text" name="password" value="123">
        <input type="file" name="img">

        <input type="submit" value="提交">

        <img src="" alt="">
    </form>
    <progress max="100" value="50"></progress>
    <script src="/upload/ajax.js"></script>

    <script>
        var form = document.querySelector("form");

        // 获取它的自定义属性
        var fileInput = document.querySelector('input[type="file"]')

        var img = document.querySelector("img");

        var progress = document.querySelector("progress");

        fileInput.addEventListener("change",function(e){
            console.log(e.target.files);
            var file = e.target.files[0];

            // 这个括号里面如果写form的话就可以把表单里面的username，password和img给到fd
            var fd = new FormData();

            fd.append("file",file);

            var xhr = new XMLHttpRequest();

            xhr.open("post","/upload");

            
            xhr.upload.onloadstart = function(e){
                console.log("上传开始");
                console.log(e);
                progress.value = 0;
                progress.style.display = "block";
            }

            xhr.upload.onprogress= function(e){
                console.log("上传中");
                console.log(e);
                progress.max = e.total;
                progress.value = e.loaded;
            }

            xhr.upload.onloadend= function(e){
                console.log("上传结束");
                console.log(e);
                progress.style.display = "none";
            }

            xhr.send(fd);

        })
        
    </script>
</body>

</html>